<?php
/**
 * 自动model metadata代码生成
 * @author yangdongqi <yangdongqi@hayzone.com>
 * @package lib.components.code
 */
class CAutoMDCode extends CComponent {

	/**
	 * 允许更新的主机
	 * 例如：localhost, 192.168.11.84
	 * @var array
	 */
	public $allowHosts = array();
	
	/**
	 * 是否允许保存新的模型
	 * @var boolean
	 */
	public $allowSaveNewModel = true;

	/**
	 * 是否关闭操作
	 * @var boolean
	 */
	public $shutdown = false;
	
	/**
	 * ModelCode 默认的 attributes
	 * @var array
	 */
	protected $_defaultCodeConfig = array (
	    'tablePrefix' => '',
	    'tableName' => '*',
	    'modelClass' => '',
	    'metadataClass' => '',
	    'baseClass' => 'CActiveRecordAdv',
	    'metadataBaseClass' => 'CARMDC',
	    'modelPath' => 'application.models',
	    'metadataPath' => 'application.models.metadata',
	    'applyColumnComment' => true,
	    'buildRelations' => true,
	    'template' => 'default',
	);
	
	/**
	 * 用户自定义的modelCode的attributes
	 * 获取codeConfig时，将和$_defaultCodeConfig合并
	 * @var array
	 */
	public $codeConfig = array();
	
	public function init() {
		Yii::import('lib.models.ar.adv.*');
		$connectionString = Yii::app()->db->connectionString;

		preg_match('/host=(.*);/', $connectionString, $matches);
		if($this->shutdown || !in_array($matches[1], $this->allowHosts)) return false;
		
		$config = $this->getCodeConfig();
		Yii::import('gii.generators.model.*');
		
		$modelCode = new ModelCode();
		$modelCode->attributes = $config;
		$modelCode->status=CCodeModel::STATUS_PREVIEW;
		$metadataBaseClass = $modelCode->metadataBaseClass;
		
		if(!(new $metadataBaseClass instanceof CARMDC)) return false;
		
		$oldController = Yii::app()->controller;
		$controller = Yii::app()->createController('/gii/model');
		Yii::app()->controller = $controller[0];
		
		if($modelCode->validate()) {
			$modelCode->prepare();
			foreach($modelCode->files as $file) {
				if($file->baseClassName == $metadataBaseClass) {
					if($file->operation == CCodeFile::OP_OVERWRITE || $file->operation == CCodeFile::OP_NEW) {
						if($file->save()) {
							Yii::trace(__CLASS__.'：file保存成功：'.'['.$file->relativePath.']', 'application.runtime');
						} else {
							Yii::trace(__CLASS__.'：file保存错误：'.'['.$file->relativePath.']'.$file->error, 'application.runtime');
						}
					}
				} else if($file->operation == CCodeFile::OP_NEW) {
					$file->save();
				}
			}
		} else {
			Yii::trace(__CLASS__.'：modelCode配置错误：'.var_export($modelCode->errors, true), 'application.runtime');
		}
		
		Yii::app()->controller = $oldController;
	}
	
	protected function getCodeConfig() {
		return array_merge($this->_defaultCodeConfig, $this->codeConfig);
	}
	

}

?>